import { Button, Input, Tooltip } from "antd";
import { Emoji } from "@/components/Emoji";
import { Message } from "@/components/Message";
import { Avatar } from "@/components/Avatar";
import { useState, useRef, PropsWithChildren, useMemo } from "react";
import { useUserStore } from "@/store/user";
import { IMessage, MessageType } from "@/apis/message";
import { ISocketMessage } from "@/pages/Home/Chatroom/";
import { upload } from "@/utils/upload";
import { getFileType } from "@/utils/file";
import { RoomDetail } from "@/apis/chatroom";

const { TextArea } = Input;

interface ChatProps {
  messages: IMessage[];
  roomInfo: RoomDetail;
  isOpen: boolean;
  isVideo: boolean;
  addMessage: (message: ISocketMessage) => void;
  addMember: (roomInfo: RoomDetail) => void;
  call: (isVideo: boolean) => void;
  removeMember: (roomInfo: RoomDetail) => void;
}

export function Chat(props: PropsWithChildren<ChatProps>) {
  const {
    messages,
    roomInfo,
    isOpen,
    isVideo,
    addMessage,
    addMember,
    removeMember,
    call,
    children,
  } = props;

  const [value, setValue] = useState("");
  const { userInfo } = useUserStore();

  const imageInputRef = useRef<HTMLInputElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const type = getFileType(file) as MessageType;
      const [success, fileData] = await upload(file);
      if (success) {
        addMessage({
          content: fileData.url,
          type: type,
        });
      }
    }
  };

  const users = useMemo(() => {
    if (roomInfo?.chatType === "Private") {
      return roomInfo.users?.filter((user) => user.id !== userInfo?.id);
    }
    return roomInfo?.users;
  }, [roomInfo]);

  return (
    <div className="flex flex-col h-full w-full">
      <div className="flex justify-between h-[60px]">
        <div className="flex just-start items-center">
          <div className="flex">
            {users?.map((user, i) => {
              return (
                <div
                  key={user.id} // 确保 key 放在最外层元素上
                  style={{
                    transform: `translateX(-${i * 50}%)`, // 每个头像左移 50% 的宽度
                    zIndex: users.length - i, // 使用 zIndex 控制重叠顺序
                  }}
                >
                  <Avatar key={user.id} src={user.avatar} />
                </div>
              );
            })}
          </div>
          <div
            style={{
              transform: `translateX(-${(users?.length - 1) * 50}%)`, // 每个头像左移 50% 的宽度
            }}
          >
            <Tooltip title="新增成员">
              <span
                className="iconfont icon-plus !text-[28px] text-[#979DA7] border-2 border-[#979DA7] rounded-full cursor-pointer hover:border-white hover:text-white"
                onClick={() => addMember(roomInfo)}
              ></span>
            </Tooltip>
          </div>
          <div
            style={{
              transform: `translateX(-${(users?.length - 1) * 50}%)`, // 每个头像左移 50% 的宽度
              marginLeft: "4px",
            }}
          >
            <Tooltip title="移除成员">
              <span
                className="iconfont icon-yichu !text-[28px] text-[#979DA7] border-2 border-[#979DA7] rounded-full cursor-pointer hover:border-white hover:text-white"
                onClick={() => removeMember(roomInfo)}
              ></span>
            </Tooltip>
          </div>
        </div>
        <div className="text-[#979DA7]">
          <span
            className={`iconfont icon-shipin ml-8 hover:text-[#1D90F5] cursor-pointer ${
              isVideo && isOpen && "!text-[#f10]"
            }`}
            key="Video"
            onClick={() => call(true)}
          ></span>
          <span
            className={`iconfont icon-gf-telephone ml-8 hover:text-[#1D90F5] cursor-pointer  ${
              !isVideo && isOpen && "!text-[#f10]"
            }`}
            key="Audio"
            onClick={() => call(false)}
          ></span>
          <span
            className={`iconfont icon-wenjian ml-8 hover:text-[#1D90F5] cursor-pointer`}
            key="File"
            onClick={() => fileInputRef.current?.click()}
          >
            <input
              ref={fileInputRef}
              type="file"
              accept="image/*,video/*,audio/*"
              hidden
              onChange={handleUpload}
            />
            {/* accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,image/*,video/*,audio/*" */}
          </span>
          <span
            className={`iconfont icon-tupian ml-8 hover:text-[#1D90F5] cursor-pointer`}
            key="Image"
            onClick={() => imageInputRef.current?.click()}
          >
            <input
              ref={imageInputRef}
              type="file"
              accept="image/*"
              hidden
              onChange={handleUpload}
            />
          </span>
        </div>
      </div>
      <div className="flex flex-col flex-1 max-h-[88%] bg-[#323644] rounded-3xl mt-4 px-6 pt-6">
        <div className="message-box flex-1 overflow-y-auto scrollbar-custom rounded-lg">
          <div className="messages">
            {messages.map((msg) => {
              return (
                <div
                  className={`message flex items-center mb-6 ${
                    msg.senderId === userInfo?.id
                      ? "flex-row-reverse"
                      : "flex-row"
                  }`}
                  key={msg.createTime}
                >
                  <Message {...msg} isSender={msg.senderId === userInfo?.id} />
                </div>
              );
            })}
            {children}
          </div>
        </div>
        <div className="min-h-[40px] mt-4 mb-6 flex justify-between items-center input-area">
          <Emoji onSelect={(emoji) => setValue((prev) => prev + emoji)} />
          <TextArea
            value={value}
            size="large"
            onChange={(e) => setValue(e.target.value)}
            autoSize={{ minRows: 1, maxRows: 6 }}
            className="rounded-xl mx-4 scrollbar-custom"
            onKeyDown={(e) => {
              if (e.key === "Enter") {
                if (value) {
                  setValue("");
                  addMessage({ type: "Text", content: value });
                  e.preventDefault();
                }
              }
            }}
          />
          <Button
            type="primary"
            className="h-10 rounded-xl"
            onClick={() => {
              if (value) {
                setValue("");
                addMessage({ type: "Text", content: value });
              }
            }}
          >
            <img src="src\assets\img\emoji\rocket.png" className="w-6 h-6" />
          </Button>
        </div>
      </div>
    </div>
  );
}
